package com.du.springmvc.converter;

import com.du.springmvc.bean.Employee;
import com.du.springmvc.bean.Gender;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

/**
 * @author : DuJiabao
 * @Project : spring-mvc
 * @Time : 2021/4/2 16:27
 * @Desc :
 */
//@Component
public class StringToEmployeeConverter implements Converter<String, Employee> {
  /**
   * 输入格式：id-name-genderCode
   *
   * @param source
   * @return
   */
  @Override
  public Employee convert(String source) {
    String[] sources = source.split("-");
    return new Employee(Integer.parseInt(sources[0]), sources[1], getGenderFromCode(sources[2]));
  }

  /**
   * 将String转换为Gender；0代表女；1代表男；
   * @param code
   * @return
   */
  private static Gender getGenderFromCode(String code) {
    if (code.equals("0")) return Gender.female;
    if (code.equals("1")) return Gender.male;
    return null;
  }
}
